// pages/search/search.js
import request from "../../utils/request";
let isSend = false;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    searchContent:'',
    hotList:[],
    inputSearchContent:'',
    searchList:[],
    historyList:[],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    this.getSearchContentData();

    this.getHotListData();

    this.getSearchHistory();
  },

  async getSearchContentData(){
    let searchContentData = await request('/search/default')
    this.setData({
      searchContent :searchContentData.data.showKeyword
    })
  },

  async getHotListData(){
    let hotListData = await request('/search/hot/detail')
    this.setData({
      hotList :hotListData.data
    })
  },

   handleInputChange(event){
    this.setData({
      inputSearchContent: event.detail.value.trim()
    })

    if (!this.data.inputSearchContent){
      this.setData({
        searchList: []
      })
      return;
    }

    //函数节流、防抖
    if (isSend){
      return
    }
    isSend = true
      setTimeout(async () => {
        let {historyList,inputSearchContent} = this.data
          let searchListData = await request('/search', {keywords: inputSearchContent, limit: 10})
          this.setData({
            searchList: searchListData.result.songs
          })
        isSend = false

        if (historyList.indexOf(inputSearchContent)!==-1){
          historyList.splice(historyList.indexOf(inputSearchContent),1);
        }
        historyList.unshift(inputSearchContent);
        this.setData({
          historyList
        })

        wx.setStorageSync('searchHistory',historyList)

      }, 300)

  },

  //获取本地记录
  getSearchHistory(){
    let historyList =  wx.getStorageSync('searchHistory')
    if (historyList){
      this.setData({
        historyList
      })
    }
  },

  //清空搜索内容
  handleClear(){
    this.setData({
      inputSearchContent:'',
      searchList:[],
    })
  },

  //删除搜索历史记录
  deleteHistory(){
    wx.showModal({
      content: '确认删除吗？',
      success: (res) => {
        if (res.confirm) {
          this.setData({
            historyList:[],
          })
          wx.removeStorageSync('searchHistory')
        }
      }
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})